package com.mingqijia.gassafety.shared.utils.user;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gap.basic.utils.CollectionUtils;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.SystemConst;
import com.mingqijia.gassafety.shared.dto.cms.CmsInfoResDTO;
import com.mingqijia.gassafety.shared.dto.user.PhoneUserDTO;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class UserRemoteService {

    @Value(value = "${asst.service.endpoint}")
    public String endpoint;


    public List<PhoneUserDTO> getUsersByPhoneList(List<String> phoneList) {
        List<PhoneUserDTO> resp = new ArrayList<>();

        try {
            JSONObject jsonObject = JSONUtil.createObj().set("method", Constants.USER_ID_BY_PHONE);
            jsonObject.set(Constants.JSON_RPC, Constants.JSON_RPC_VERSION);

            JSONArray params = JSONUtil.createArray();
            JSONObject paramObject = JSONUtil.createObj();
            paramObject.set("phone", phoneList);
            params.add(paramObject);
            jsonObject.set("params", params);
            log.info("getUsersByPhoneList-url：{}，request：{}", endpoint, jsonObject.toString());

            String result = HttpRequest.post(endpoint + Constants.RPC_METHOD)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .header("x-from-service", "internal-service")
                .header("X-ENTERPRISE-ID", "10000")
                .header("X-TRACE-ID", MDC.get( SystemConst.MDC_KEY_TRACE_ID.val()))
                .body(jsonObject.toString())
                .execute()
                .body();

            log.info("getUsersByPhoneList-url：{}，response：{}", endpoint, result);
            if (StringUtils.isNotEmpty(result)) {
                JSONObject resultObject = JSONUtil.parseObj(result).getJSONObject("result");
                JSONArray resultArray = resultObject.getJSONArray("data");
                List<PhoneUserDTO> resultList = JSONUtil.toList(resultArray, PhoneUserDTO.class);
                if (CollectionUtils.isNotEmpty(resultList)) {
                    resp.addAll(resultList);
                }
            }

        } catch (Exception e) {
            log.error("getUsersByPhoneList-error:", e);
        }
        return resp;
    }

}
